package com.laiketui.root.utils.tool;

import com.laiketui.root.consts.ErrorCode;
import com.laiketui.root.consts.GloabConst;
import com.laiketui.root.exception.LaiKeApiException;
import com.laiketui.root.utils.common.LKTSnowflakeIdWorker;
import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.Date;

/**
 * 图片base64互转工具类
 *
 * @author Trick
 * @date 2020/10/27 17:16
 */
public class ImageBase64ConverterUtils {

    private static final Logger logger = LoggerFactory.getLogger(ImageBase64ConverterUtils.class);


    /**
     * 本地文件（图片、excel等）转换成Base64字符串
     *
     * @param imgPath -
     * @return String
     * @throws LaiKeApiException -
     * @author Trick
     * @date 2020/10/27 17:53
     */
    public static String convertFileToBase64(String imgPath) throws LaiKeApiException {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            System.out.println("文件大小（字节）=" + in.available());
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("图片转64异常" + e.getMessage());
            throw new LaiKeApiException(ErrorCode.BizErrorCode.BUSY_NETWORK, "网络异常", "convertBase64ToFile");
        }
        // 对字节数组进行Base64编码，得到Base64编码的字符串
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }


    /**
     * 将base64字符串，生成文件
     *
     * @param fileBase64String -
     * @param filePath         -
     * @param fileName         -
     * @throws LaiKeApiException -
     * @author Trick
     * @date 2020/10/27 17:53
     */
    public static void convertBase64ToFile(String fileBase64String, String filePath) throws LaiKeApiException {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            StringBuilder sysPath = new StringBuilder(filePath);
            String dateStr = FastDateFormat.getInstance(GloabConst.TimePattern.YMD1).format(new Date());
            sysPath.append(File.separator);
            sysPath.append(dateStr);
            sysPath.append(File.separator);

            File dir = new File(sysPath.toString());
            //判断文件目录是否存在
            if (!dir.exists()) {
                boolean flag = dir.mkdirs();
                if (!flag) {
                    throw new LaiKeApiException(ErrorCode.BizErrorCode.INSUFFICIENT_PRIVILEGE, "权限不够", "convertBase64ToFile");
                }
            }
            //获取图片格式
            String[] base64 = fileBase64String.split(",");
            String fileName = base64[0];
            fileBase64String = base64[1];
            fileName = fileName.substring(fileName.indexOf("/") + 1, fileName.indexOf(";base64"));

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bfile = decoder.decodeBuffer(fileBase64String);


            //组装路径
            sysPath.append(File.separator);
            LKTSnowflakeIdWorker buildeId = new LKTSnowflakeIdWorker();
            sysPath.append(buildeId.nextId());
            sysPath.append(".");
            sysPath.append(fileName);

            file = new File(sysPath.toString());
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (LaiKeApiException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("base64转换成图片异常" + e.getMessage());
            throw new LaiKeApiException(ErrorCode.BizErrorCode.BUSY_NETWORK, "网络异常", "convertBase64ToFile");
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        String base64Str = "";
        convertBase64ToFile(base64Str, "D:");
    }

}
